from django.http import HttpResponse, JsonResponse, FileResponse, Http404
from django.views import View
import os
import json
from django.conf import settings
from utils.response import CommonResponseMixin, ReturnCode
from ..models import Movie
from django.core.paginator import Paginator


class MovieImageView(View, CommonResponseMixin):
    def get(self, request):
        img_md5 = request.GET.get("md5", "")
        img_file = os.path.join(settings.MOVIE_IMAGES_DIR, img_md5 + ".jpg")
        if not os.path.exists(img_file):
            response = self.wrap_json_response(code=ReturnCode.RESOURCE_NOT_FOUND)
            return JsonResponse(data=response, safe=False)
        else:
            # data = open(img_file, "rb").read()
            return FileResponse(open(img_file, "rb"), content_type="image/jpg")

    def post(self, request):
        message = "POST method success!"
        response_dict = self.wrap_json_response(message=message)
        return JsonResponse(data=response_dict, safe=False)


class MovieImageTextView(View, CommonResponseMixin):
    def get(self, request):
        img_md5 = request.GET.get("md5", "")
        img_file = os.path.join(settings.MOVIE_IMAGES_DIR, img_md5 + ".jpg")
        if not os.path.exists(img_file):
            response = self.wrap_json_response(code=ReturnCode.RESOURCE_NOT_FOUND)
            return JsonResponse(data=response, safe=False)
        else:
            response_data = dict(name=(img_md5 + ".jpg"), url="/resources/movie_image?md5={}".format(img_md5))
            response = self.wrap_json_response(data=response_data)
            return JsonResponse(data=response, safe=False)

    def post(self, request):
        message = "POST method success! View method is not completed yet."
        response_dict = self.wrap_json_response(message=message)
        return JsonResponse(data=response_dict, safe=False)


class MovieInfoView(View, CommonResponseMixin):
    def get(self, request):
        page = request.GET.get("page")
        if page:
            page = int(page)
        print(f"current page: {page}")

        ret_json = {"movies": {}, "page_info": {}}
        movies = Movie.objects.all().values()
        paginator = Paginator(movies, 10)
        page_range = paginator.num_pages  # 页面数量
        print(f"page num:  {page_range}")
        page_movie_list = paginator.page(page)  # 当前页

        for movie in page_movie_list:
            ret_json["movies"][movie["translated_name"]] = movie
        ret_json["page_info"]["current_page"] = page
        ret_json["page_info"]["page_range"] = list(range(1, page_range+1))
        return JsonResponse(data=ret_json, safe=False, status=200)




